﻿using AngleSharp.Dom;
using AngleSharp.Parser.Html;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace BaseEpub
{
    public abstract class NcxBase
    {
        public abstract void GetContent(string ncxPath);

        /// <summary>
        /// 替换图片
        /// </summary>
        public abstract void ReplaceImg(string content);
    }
    [Obsolete]
    public class NdsNcx : NcxBase
    {
        public override void GetContent(string ncxPath)
        {
            XDocument xd = XDocument.Load(ncxPath);
            //string path= System.IO.Directory.GetDirectoryRoot(ncxPath);
            XElement root = xd.Root;
            XElement navMap = root.Elements().Where(m => m.Name.LocalName == "navMap").First();
            IList<XElement> navPoints = navMap.Elements().Where(m => m.Name.LocalName == "navPoint").ToList(); //获取章列表
            //章节同级别的顺序
            //int orderBy = 1;
            foreach (var chapter in navPoints)
            {
                //目录整体顺序
                string chaOrderBy = chapter.Attribute("playOrder").Value;
                IList<XElement> navLabel = chapter.Elements().Where(m => m.Name.LocalName == "navLabel").ToList();
                //章的名称
                string chaName = navLabel.ElementAt(0).Value;
                XElement content = chapter.Elements().Where(m => m.Name.LocalName == "content").First();
                string src = content.Attribute("src").Value;
                orderBy++;
                IList<XElement> secList = chapter.Elements().Where(m => m.Name.LocalName == "navPoint").ToList(); //获取节列表

                GetPage(src, 1);

                //递归子目录
                DgNav(secList);
            }
        }

        ReplacePageImg repImg = new ReplacePageImg();

        private short orderBy = 1;

        /// <summary>
        /// 递归目录
        /// </summary>
        private void DgNav(IList<XElement> xeles)
        {
            if (xeles != null && xeles.Count > 0)
            {
                orderBy = 1;
                foreach (var sec in xeles)
                {
                    //目录整体顺序
                    string chaOrderBy = sec.Attribute("playOrder").Value;
                    IList<XElement> navLabel = sec.Elements().Where(m => m.Name.LocalName == "navLabel").ToList();
                    //章的名称
                    string chaName = navLabel.ElementAt(0).Value;
                    XElement content = sec.Elements().Where(m => m.Name.LocalName == "content").First();
                    string src = content.Attribute("src").Value;
                    orderBy++;
                    IList<XElement> secList = sec.Elements().Where(m => m.Name.LocalName == "navPoint").ToList(); //获取节列表
                    GetPage(src, 1);
                    //递归子目录
                    DgNav(secList);
                }
            }
        }

        public void GetPage(string srcPath, Int64 secId)
        {
            //第一个为文件夹，第二个为文件名称
            if (!srcPath.Contains("#"))  
            {
                string[] dir = srcPath.Split('/');


                //获取目录对应的正文内容路径，
                string pagePath = @"E:\MyCode\NetCode\AngleSharpDemo\有机化学样本3\有机化学样本3\OEBPS\" + dir.First() + @"\" + dir[1];

                IElement bodyNode = GetBodyHtml(pagePath);


                if (bodyNode != null)
                {
                    string pageVal = bodyNode.InnerHtml;
                }
            }
            else //包含”#“ 是目录跳转
            {
                string[] dir = srcPath.Split('/');
                string[] ct= dir[1].Split('#');
                string pagePath = @"E:\MyCode\NetCode\AngleSharpDemo\有机化学样本3\有机化学样本3\OEBPS\" + dir.First() + @"\" + ct[0];
                IElement bodyNode = GetBodyHtml(pagePath);
                //找到id的节点 如：”<h2 id="sigil_toc_id_1" class="heading-0">第一节　有机化合物和有机化学</h2>“
                IElement ll= bodyNode.QuerySelector("#"+ct[1]);
                //bodyNode.QuerySelector
                if (ll != null)
                {
                    
                    //获取该节点的顶层节点（不过却是是body下的子节点）
                    GetBodyElement(ll);
                    IElement currentEle = bodyChildEle;

                    

                    StringBuilder sbContent = new StringBuilder();
                    //sbContent.Append(currentEle.OuterHtml);
                    ////一直遍历下一个节点去，直到找到id，或者到最后没有“#”锚点
                    //IElement nextNode = currentEle.NextElementSibling;
                    //string id = nextNode.GetAttribute("id");
                    ////todo:注意可能每个出版社的不一样 id.Contains("sigil_toc_id")
                    //if (!nextNode.HasAttribute("id") && id.Contains("sigil_toc_id"))
                    //{
                    //    sbContent.Append(currentEle.OuterHtml);
                    //}
                    GetSecPage(currentEle, sbContent);
                    string pageContent = secContent;
                    //替换图片路径
                    repImg.ReplaceImg(pageContent);
                }
            }
            
        }

        //body下的顶级标签
        private IElement bodyChildEle = null;

        private void GetBodyElement(IElement ele)
        {
            IElement parentElement=ele.ParentElement;
            if (parentElement.LocalName == "body")
            {
                bodyChildEle = ele;
            }
            else
            {
                GetBodyElement(parentElement);
            }
        }

        private string secContent = "";

        private void GetSecPage(IElement ll, StringBuilder sbContent)
        {
            if (ll != null)
            {
                //给每个顶层段落添加guid
                ll.SetAttribute("hexid", Guid.NewGuid().ToString("N"));

                sbContent.Append(ll.OuterHtml);
                IElement nextNode = ll.NextElementSibling;
                if (nextNode == null) //最后一个节点，走的body最后了
                {
                    secContent = sbContent.ToString();
                    return;
                }
                string id = nextNode.GetAttribute("id");
                //todo:注意可能每个出版社的不一样 id.Contains("sigil_toc_id")
                if (nextNode.HasAttribute("id") && id.Contains("sigil_toc_id"))
                {
                    secContent = sbContent.ToString();
                }
                else
                {
                    sbContent.Append(ll.OuterHtml);
                    GetSecPage(nextNode, sbContent);
                }
            }
        }

        HtmlParser parser = new HtmlParser();

        private IElement GetBodyHtml(string pagePath)
        {
            string pageHtml = System.IO.File.ReadAllText(pagePath);
            
            var doc = parser.Parse(pageHtml);
            IElement bodyNode = doc.All.Where(m => m.LocalName == "body").First();
            return bodyNode;
        }

        public override void ReplaceImg(string content)
        {
            throw new NotImplementedException();
        }
    }
}
